<template>
  <div class="app-container">

    <div class="filter-container" style="margin-bottom: 20px;">
      <el-input v-model="listQuery.userId" placeholder="角色ID" style="width: 100px;" class="filter-item" @keyup.enter.native="handleFilter" @blur="handleFilter" />
      <el-input v-model="listQuery.userName" placeholder="姓名" style="width: 100px;" class="filter-item"  />
      <el-date-picker
      v-model="listQuery.startTime"
      type="datetime"
      value-format="yyyy-MM-dd HH:mm:ss"
      placeholder="创建时间">
    </el-date-picker>
    <el-date-picker
      v-model="listQuery.endTime"
      type="datetime"
      value-format="yyyy-MM-dd HH:mm:ss"
      placeholder="更新时间">
    </el-date-picker>  <el-button  class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="success" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
    </div>

    <el-table
      height="550px"
      :data="list"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="ID" width="95">
        <template slot-scope="scope">
          {{ scope.$index }}
        </template>
      </el-table-column>
      <el-table-column label="角色ID" width="80" align="center">
        <template slot-scope="scope">
          {{ scope.row.userId }}
        </template>
      </el-table-column>
      <el-table-column label="姓名" align="center">
        <template slot-scope="scope">
          {{ scope.row.userName }}
        </template>
      </el-table-column>
      <el-table-column label="邮箱" align="center" width="140">
        <template slot-scope="scope">
          {{ scope.row.userEmail }}
        </template>
      </el-table-column>
      <el-table-column label="昵称" align="center">
        <template slot-scope="scope">
          {{ scope.row.nickName }}
        </template>
      </el-table-column>
      <el-table-column label="设备ID" align="center">
        <template slot-scope="scope">
          {{ scope.row.deviceId }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" width="160">
        <template slot-scope="scope">
          {{ scope.row.createTime }}
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" width="160">
        <template slot-scope="scope">
          {{ scope.row.updateTime }}
        </template>
      </el-table-column>
     <el-table-column label="状态" class-name="status-col" width="100" align="center">
        <template slot-scope="scope">
          <!-- <el-tag :type="scope.row.status | statusFilter">
            可用
          </el-tag> -->
          <el-tag type="success" v-if="scope.row.status!=1">
            可用
          </el-tag>
          <el-tag type="info" v-if="scope.row.status!=0">
            禁用
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" class="el-icon-edit" round size="mini" @click="editUser(scope.row)" v-if="hasAuth('users:update')">
          </el-button>

          <el-tooltip class="item" effect="dark" content="禁用" placement="bottom">
            <el-button v-if="scope.row.status!=1" class="el-icon-success" size="mini" type="success" round @click="handleModifyStatus(scope.row,1)">
            </el-button>
          </el-tooltip>

          <el-tooltip class="item" effect="dark" content="可用" placement="bottom">
            <el-button v-if="scope.row.status!= 0" class="el-icon-error" size="mini" round @click="handleModifyStatus(scope.row,0)">
            </el-button>
          </el-tooltip>

          <el-tooltip class="item" effect="dark" content="权限" placement="bottom">
            <el-button  size="mini" class="el-icon-setting" type="warning" round @click="RoleUser(scope.row)">
            </el-button>
          </el-tooltip>

          <el-button size="mini" class="el-icon-delete" type="danger" round @click="delUser(scope.row.id)">
          </el-button>
        </template>
      </el-table-column>
    </el-table>
     <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
  
   <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm"  :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        
        <el-form-item label="用户ID" prop="userId" >
          <el-input v-model="temp.userId" placeholder="请输入1-5"/>
        </el-form-item>
        <el-form-item label="姓名" prop="userName">
          <el-input v-model="temp.userName" />
        </el-form-item>
        <el-form-item label="邮箱" prop="userEmail">
          <el-input v-model="temp.userEmail" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickName">
          <el-input v-model="temp.nickName" />
        </el-form-item>
        <el-form-item label="设备ID" prop="deviceId">
          <el-input v-model="temp.deviceId" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-input v-model="temp.status" />
        </el-form-item>
        <!-- <el-form-item label="Status">
          <el-select v-model="temp.status" class="filter-item" placeholder="Please select">
            <el-option v-for="item in statusOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>    

    <el-dialog title="权限分配" :visible.sync="dialogRoleVisible">
      <el-form ref="roleForm"  :model="temp" label-position="left" label-width="70px" style="width: 250px; margin-left:50px;">
        <el-form-item label="姓名" prop="userName">
          {{temp.userName}}
        </el-form-item>
        <el-form-item label="权限">
          <el-select v-model="currRoleId" class="filter-item" placeholder="Please select">
            <el-option 
            v-for="(item,index) in AuthOptions" 
            :key="index" :label="item.roleName" 
            :value="item.roleId">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogRoleVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="changeAuth(temp)">
          确定
        </el-button>
      </div>
    </el-dialog>    
  
  
  </div>
</template>

<script>
import {setUserId,getRoleIdByuserId,getAllAuth, lockUser,getUserList , updateUser,addUser,deluser} from '@/api/userList'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name:'userList',
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: 'success',
        1: 'info'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      currRoleId:undefined,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        userId:undefined,
        userName:undefined,
        startTime:undefined,
        endTime:undefined
      },
      textMap: {
        update: '编辑',
        create: '添加'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      dialogRoleVisible: false,
      AuthOptions: [],
      temp: {
        id: '',
        userId:'',
        userName: '',
        userEmail: '',
        nickName: '',
        deviceId: '',
        status: ''
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    editUser(row){
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
      this.$refs['dataForm'].clearValidate()
      })
    },
   updateData(){
       this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateUser(tempData).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
     })
    },
     resetTemp() {
      this.temp = {
        id: undefined,
        userName: '',
        userEmail: '',
        nickName: '',
        deviceId: '',
        status: ''
      }
    },
     handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addUser(this.temp).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: '成功',
              message: '添加成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    delUser(id){
       this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deluser(id).then(() => {
            this.getList()
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
         })
         }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      
    },
    getList() {
      this.listLoading = true
      getUserList(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.count
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
     handleFilter() {
      this.getList()
    },
    handleModifyStatus(row, status) {
      row.status = status
      lockUser(row.id,status).then(() => {
          this.dialogFormVisible = false
          
          this.$message({
            title: '成功',
            message: '操作成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
    },
     RoleUser(row){
      this.temp = Object.assign({}, row) // copy obj
      this.dialogRoleVisible = true

      getRoleIdByuserId(row.userId).then((response)=>{
        this.currRoleId = response.data
      })
      getAllAuth().then((response) => {
          this.AuthOptions = response.data
         this.$nextTick(() => {
         this.$refs['roleForm'].clearValidate()
      })

     
      })
    },
    changeAuth(temp){
      setUserId(temp.id,this.currRoleId).then(()=>{
         this.dialogRoleVisible = false
          this.$message({
            title: '成功',
            message: '操作成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消权限修改'
          });          
        });
    }
  }
}
</script>
